<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-icon">
          <uni-icons type="spinner-cycle" size="30" color="#3B82F6"></uni-icons>
        </view>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>

    <view v-else>
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="nav-item" :class="{ active: currentView === 'day' }" @click="switchView('day')">
          今日血氧
        </view>
        <view class="nav-item" :class="{ active: currentView === 'week' }" @click="switchView('week')">
          本周趋势
        </view>
      </view>

      <!-- 今日血氧监测 -->
      <view v-if="currentView === 'day'" class="day-view">
        <!-- 血氧概览卡片 -->
        <view class="card">
          <view class="card-header">
            <text class="title">今日血氧监测</text>
            <view class="stats">
              <text class="stat-value">{{ spo2.day.avg }}%</text>
              <text class="stat-label">平均血氧</text>
            </view>
          </view>

          <!-- 血氧柱状图 -->
          <view class="charts-box">
            <qiun-data-charts v-if="spo2DayData" type="column" :opts="spo2ColumnOpts" :chartData="spo2DayData" />
          </view>

          <!-- 血氧数据摘要 -->
          <view class="spo2-summary">
            <view class="spo2-item">
              <text class="spo2-label">最高血氧</text>
              <text class="spo2-value">{{ spo2.day.max }}%</text>
              <text class="spo2-time">{{ spo2.day.maxTime }}</text>
            </view>
            <view class="spo2-divider"></view>
            <view class="spo2-item">
              <text class="spo2-label">最低血氧</text>
              <text class="spo2-value">{{ spo2.day.min }}%</text>
              <text class="spo2-time">{{ spo2.day.minTime }}</text>
            </view>
          </view>
        </view>

        <!-- 血氧状态卡片 -->
        <view class="card spo2-status-card">
          <view class="card-header">
            <text class="title">血氧状态</text>
            <view class="status-indicator" :class="getSpo2StatusClass(spo2.day.avg)">
              {{ getSpo2StatusText(spo2.day.avg) }}
            </view>
          </view>
          <view class="status-scale">
            <view class="scale-segment" v-for="(segment, index) in spo2Scale" :key="index"
              :style="{ flex: segment.width, backgroundColor: segment.color }">
              <text class="scale-label">{{ segment.label }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 本周血氧监测 -->
      <view v-else class="week-view">
        <!-- 周趋势图表 -->
        <view class="card">
          <view class="card-header">
            <text class="title">本周血氧趋势</text>
            <view class="stats">
              <text class="stat-value">{{ spo2.week.avg }}%</text>
              <text class="stat-label">周平均</text>
            </view>
          </view>
          <view class="charts-box">
            <qiun-data-charts type="line" :opts="spo2LineOpts" :chartData="spo2WeekData" />
          </view>
        </view>

        <!-- 每日血氧数据 -->
        <view class="card">
          <view class="card-header">
            <text class="title">每日血氧数据</text>
          </view>
          <view class="week-spo2-grid">
            <view class="week-spo2-item" v-for="(day, index) in spo2.week.days" :key="index"
              :class="getSpo2StatusClass(day.avg)">
              <text class="week-day">{{ day.name }}</text>
              <view class="week-spo2-value">
                <text class="value">{{ day.avg }}</text>
                <text class="unit">%</text>
              </view>
              <view class="week-spo2-range">
                <text class="min">{{ day.min }}</text>
                <text class="separator">~</text>
                <text class="max">{{ day.max }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useHealthData } from '../../../store/modules/useHealthData'
import { get } from '@/utils/request'
// import { uniIcons } from '@dcloudio/uni-ui'

const healthDataStore = useHealthData()

// 视图状态
const currentView = ref('day')
const isLoading = ref(true)

// 血氧数据
const spo2 = ref({
  day: {
    avg: 0,
    max: 0,
    maxTime: "--:--",
    min: 0,
    minTime: "--:--",
    timeSeriesData: []
  },
  week: {
    avg: 0,
    days: [
      { name: "周一", avg: 0, min: 0, max: 0 },
      { name: "周二", avg: 0, min: 0, max: 0 },
      { name: "周三", avg: 0, min: 0, max: 0 },
      { name: "周四", avg: 0, min: 0, max: 0 },
      { name: "周五", avg: 0, min: 0, max: 0 },
      { name: "周六", avg: 0, min: 0, max: 0 },
      { name: "周日", avg: 0, min: 0, max: 0 }
    ]
  }
})

const spo2Scale = ref([
  { label: "危险", width: 1, color: "#EE6666", range: "<90%" },
  { label: "偏低", width: 2, color: "#FAC858", range: "90-94%" },
  { label: "正常", width: 3, color: "#91CB74", range: "95-100%" }
])

// 图表配置
const spo2ColumnOpts = ref({
  color: ["#3B82F6"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED",
    boundaryGap: "justify"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 5,
    data: [{
      min: 0,
      max: 100,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val}%`
    }]
  },
  extra: {
    column: {
      type: "group",
      width: 30,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08,
      linearType: "custom",
      seriesGap: 5,
      linearOpacity: 0.5,
      barBorderCircle: true,
      customColor: ["#3B82F6"]
    },
    markLine: {
      type: "dash",
      dashLength: 4,
      data: [
        { value: 95, lineColor: "#91CB74", lineWidth: 1, labelColor: "#91CB74", labelFontSize: 20 },
        { value: 90, lineColor: "#EE6666", lineWidth: 1, labelColor: "#EE6666", labelFontSize: 20 }
      ]
    }
  }
})

const spo2LineOpts = ref({
  color: ["#3B82F6"],
  padding: [15, 15, 10, 15],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    splitNumber: 5,
    data: [{
      min: 85,
      max: 100,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA",
      format: val => `${val}%`
    }]
  },
  extra: {
    line: {
      type: "curve",
      width: 3,
      activeType: "hollow"
    }
  }
})

// 图表数据
const spo2DayData = computed(() => {
  // 使用实际返回的 timeSeriesData
  if (!spo2.value.day || !spo2.value.day.timeSeriesData || spo2.value.day.timeSeriesData.length === 0) {
    return {
      categories: [],
      series: []
    };
  }

  // categories 使用时间间隔标签，data 使用平均值
  const categories = spo2.value.day.timeSeriesData.map(item => item.time);
  const data = spo2.value.day.timeSeriesData.map(item => item.value);

  return {
    categories: categories,
    series: [
      {
        name: "血氧",
        data: data
      }
    ]
  }
})

const spo2WeekData = computed(() => ({
  categories: spo2.value.week.days.map(day => day.name),
  series: [
    {
      name: "平均血氧",
      data: spo2.value.week.days.map(day => day.avg)
    }
  ]
}))

// 方法
const switchView = (view) => {
  currentView.value = view
  loadData()
}

const getSpo2StatusClass = (value) => {
  if (value < 90) return 'danger'
  if (value < 95) return 'warning'
  return 'normal'
}

const getSpo2StatusText = (value) => {
  if (value < 90) return '危险'
  if (value < 95) return '偏低'
  return '正常'
}

// 加载数据
const loadData = async () => {
  try {

    isLoading.value = true
    const userId = healthDataStore.getCurUserId

    const res = await get(
      `/health/${userId}/statistics?period=${currentView.value}&type=bloodOxygen`,
      'api/v1'
    )

    if (res.code === 200 && res.data) {
      if (currentView.value === 'day') {
        spo2.value.day = { ...spo2.value.day, ...res.data };
      } else {
        spo2.value.week = {
          ...spo2.value.week,
          ...res.data
        }
      }
    }
  } catch (error) {
    console.error('Failed to load blood oxygen data:', error)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  } finally {
    // 添加一个小延迟，确保数据完全准备好
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadData()
})

// 监听视图切换
watch(currentView, async () => {
  await loadData()
})
</script>

<style lang="scss" scoped>
/* 样式部分保持不变 */
/* 和你原始的style代码完全一致 */
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;

    &.active {
      color: #3B82F6;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #3B82F6;
        border-radius: 2rpx;
      }
    }
  }
}

.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #3B82F6;
    }

    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }

  .status-indicator {
    font-size: 26rpx;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;

    &.normal {
      background-color: #E6F7E6;
      color: #3CA272;
    }

    &.warning {
      background-color: #FEF7E6;
      color: #FAC858;
    }

    &.danger {
      background-color: #FFEEEE;
      color: #EE6666;
    }
  }
}

.charts-box {
  width: 100%;
  height: 400rpx;
}

.spo2-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;

  .spo2-item {
    flex: 1;
    text-align: center;

    .spo2-label {
      font-size: 26rpx;
      color: #999;
      display: block;
    }

    .spo2-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      display: block;
      margin: 8rpx 0;
    }

    .spo2-time {
      font-size: 24rpx;
      color: #999;
      display: block;
    }
  }

  .spo2-divider {
    width: 1rpx;
    background-color: #F0F0F0;
    margin: 0 20rpx;
  }
}

.spo2-status-card {
  .status-scale {
    display: flex;
    height: 60rpx;
    border-radius: 12rpx;
    overflow: hidden;
    margin-top: 20rpx;

    .scale-segment {
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      .scale-label {
        font-size: 24rpx;
        color: #fff;
        font-weight: 500;
        text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.3);
        z-index: 1;
      }
    }
  }
}

.week-spo2-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;

  .week-spo2-item {
    padding: 20rpx;
    border-radius: 12rpx;

    &.normal {
      background-color: #E6F7E6;

      .week-spo2-value .value {
        color: #3CA272;
      }
    }

    &.warning {
      background-color: #FEF7E6;

      .week-spo2-value .value {
        color: #FAC858;
      }
    }

    &.danger {
      background-color: #FFEEEE;

      .week-spo2-value .value {
        color: #EE6666;
      }
    }

    .week-day {
      font-size: 28rpx;
      color: #666;
      display: block;
      margin-bottom: 12rpx;
    }

    .week-spo2-value {
      display: flex;
      align-items: flex-end;
      margin-bottom: 8rpx;

      .value {
        font-size: 36rpx;
        font-weight: 500;
        margin-right: 8rpx;
      }

      .unit {
        font-size: 24rpx;
        color: #999;
        padding-bottom: 4rpx;
      }
    }

    .week-spo2-range {
      font-size: 24rpx;
      color: #666;

      .min,
      .max {
        font-weight: 500;
      }

      .separator {
        margin: 0 8rpx;
      }
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;

  .loading-content {
    text-align: center;
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    .loading-icon {
      margin-bottom: 20rpx;
      animation: rotate 1s linear infinite;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666;
      font-weight: 500;
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>